from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import time
import re
import os
import requests
import json
from datetime import datetime


class AppVersionCrawler:
    def __init__(self):

        options = webdriver.ChromeOptions()
        options.add_argument('--headless')
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        options.add_argument('--disable-gpu')
        options.add_argument('--window-size=1920,1080')
        options.add_argument(
            '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')


        chromedriver_path = r"C:\Users\huf06\PycharmProjects\test\APPversion\chromedriver.exe"


        self.driver = webdriver.Chrome(executable_path=chromedriver_path, options=options)
        self.wait = WebDriverWait(self.driver, 15)

    def close(self):
        """关闭浏览器"""
        self.driver.quit()

    def extract_version_from_html(self, html_content):
        """从HTML内容中提取版本号"""

        version_pattern = r'<div style="float-left">\s*版本号\s*</div>\s*<div style="float-right">\s*([\d.]+)\s*</div>'
        match = re.search(version_pattern, html_content, re.IGNORECASE)

        if match:
            return match.group(1)


        version_pattern2 = r'版本号\s*</div>\s*<div[^>]*>\s*([\d.]+)\s*</div>'
        match = re.search(version_pattern2, html_content, re.IGNORECASE)

        if match:
            return match.group(1)

        return "未找到版本信息"

    def get_xiaomi_version(self, app_id, app_name):
        """获取小米应用商店版本信息"""
        try:
            url = f"https://app.mi.com/details?id={app_id}"
            print(f"正在访问{app_name}小米应用商店: {url}")
            self.driver.get(url)


            time.sleep(5)


            page_html = self.driver.page_source


            version = self.extract_version_from_html(page_html)


            if version == "未找到版本信息":
                try:

                    version_elements = self.driver.find_elements(By.XPATH, "//div[contains(text(), '版本号')]")
                    for element in version_elements:

                        parent = element.find_element(By.XPATH, "..")

                        sibling_elements = parent.find_elements(By.XPATH, "./div")
                        for sibling in sibling_elements:
                            sibling_text = sibling.text.strip()

                            if re.match(r'^\d+\.\d+\.\d+$', sibling_text):
                                return sibling_text
                except:
                    pass

            return version
        except Exception as e:
            return f"获取{app_name}小米版本失败: {str(e)}"

    def get_huawei_version(self, hw_id, app_name):
        """获取华为应用市场版本信息"""
        try:
            url = f"https://appgallery.huawei.com/app/{hw_id}"
            print(f"正在访问{app_name}华为应用市场: {url}")
            self.driver.get(url)


            time.sleep(5)


            page_html = self.driver.page_source


            version = self.extract_version_from_html(page_html)


            if version == "未找到版本信息":
                try:
                    # 查找包含"版本号"的元素
                    version_elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), '版本')]")
                    for element in version_elements:
                        # 获取父元素
                        parent = element.find_element(By.XPATH, "..")
                        # 查找同级元素中的版本号
                        sibling_elements = parent.find_elements(By.XPATH, "./*")
                        for sibling in sibling_elements:
                            sibling_text = sibling.text.strip()
                            # 检查是否是版本号格式
                            if re.match(r'^\d+\.\d+\.\d+$', sibling_text):
                                return sibling_text
                except:
                    pass

            return version
        except Exception as e:
            return f"获取{app_name}华为版本失败: {str(e)}"

    def get_yyb_version(self, pkgname, app_name):
        """获取应用宝版本信息"""
        try:
            url = f"https://a.app.qq.com/o/simple.jsp?pkgname={pkgname}"
            print(f"正在访问{app_name}应用宝: {url}")
            self.driver.get(url)


            time.sleep(5)


            page_html = self.driver.page_source


            version = self.extract_version_from_html(page_html)


            if version == "未找到版本信息":
                try:

                    version_elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), '版本号')]")
                    for element in version_elements:

                        parent = element.find_element(By.XPATH, "..")

                        sibling_elements = parent.find_elements(By.XPATH, "./*")
                        for sibling in sibling_elements:
                            sibling_text = sibling.text.strip()

                            if re.match(r'^\d+\.\d+\.\d+$', sibling_text):
                                return sibling_text
                except:
                    pass

            return version
        except Exception as e:
            return f"获取{app_name}应用宝版本失败: {str(e)}"

    def get_vivo_version(self, vivo_url, app_name):
        """获取vivo版本信息"""
        try:
            print(f"正在访问{app_name}vivo应用商店: {vivo_url}")
            self.driver.get(vivo_url)

            time.sleep(5)


            page_html = self.driver.page_source


            version = self.extract_version_from_html(page_html)


            if version == "未找到版本信息":
                try:

                    version_elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), '版本信息')]")
                    for element in version_elements:

                        parent = element.find_element(By.XPATH, "..")

                        sibling_elements = parent.find_elements(By.XPATH, "./*")
                        for sibling in sibling_elements:
                            sibling_text = sibling.text.strip()

                            if re.match(r'^\d+\.\d+\.\d+$', sibling_text):
                                return sibling_text
                except:
                    pass

            return version
        except Exception as e:
            return f"获取{app_name}vivo版本失败: {str(e)}"

    def get_apple_version(self, apple_url, app_name):
        """获取苹果App Store版本信息"""
        try:
            print(f"正在访问{app_name}苹果App Store: {apple_url}")
            self.driver.get(apple_url)


            time.sleep(5)

            try:
                version_element = self.driver.find_element(By.XPATH,
                                                           "//p[contains(@class, 'whats-new__latest__version')]")
                if version_element:
                    return version_element.text.replace('版本 ', '')
            except:
                pass


            elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), '版本')]")
            for element in elements:
                text = element.text
                if "版本" in text:
                    version_match = re.search(r'版本\s*([\d.]+)', text)
                    if version_match:
                        return version_match.group(1)

            return "未找到版本信息"
        except Exception as e:
            return f"获取{app_name}苹果版本失败: {str(e)}"

    def get_app_versions(self, app_info):
        """获取单个应用的所有版本信息"""
        app_name = app_info["name"]
        app_id = app_info["app_id"]
        hw_id = app_info["hw_id"]
        apple_url = app_info["apple_url"]
        vivo_url = app_info["vivo_url"]

        results = {}

        # 获取各平台版本
        results[f"{app_name}-小米应用商店"] = self.get_xiaomi_version(app_id, app_name)
        results[f"{app_name}-华为应用市场"] = self.get_huawei_version(hw_id, app_name)
        results[f"{app_name}-应用宝"] = self.get_yyb_version(app_id, app_name)
        results[f"{app_name}-苹果App Store"] = self.get_apple_version(apple_url, app_name)
        results[f"{app_name}-VIVO应用商店"] = self.get_vivo_version(vivo_url, app_name)

        return results


class WeComRobot:
    """企微机器人消息发送类"""

    def __init__(self, webhook_url):
        self.webhook_url = webhook_url

    def send_markdown_message(self, title, content):
        """发送Markdown格式消息"""
        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": f"**{title}**\n{content}"
            }
        }

        try:
            response = requests.post(
                self.webhook_url,
                headers={'Content-Type': 'application/json'},
                data=json.dumps(data),
                timeout=10
            )
            if response.status_code == 200:
                print("企微消息发送成功")
                return True
            else:
                print(f"企微消息发送失败: {response.status_code}, {response.text}")
                return False
        except Exception as e:
            print(f"企微消息发送异常: {str(e)}")
            return False

    def send_text_message(self, content, mentioned_list=None):
        """发送文本消息"""
        if mentioned_list is None:
            mentioned_list = []

        data = {
            "msgtype": "text",
            "text": {
                "content": content,
                "mentioned_list": mentioned_list
            }
        }

        try:
            response = requests.post(
                self.webhook_url,
                headers={'Content-Type': 'application/json'},
                data=json.dumps(data),
                timeout=10
            )
            if response.status_code == 200:
                print("企微消息发送成功")
                return True
            else:
                print(f"企微消息发送失败: {response.status_code}, {response.text}")
                return False
        except Exception as e:
            print(f"企微消息发送异常: {str(e)}")
            return False


def format_results_for_wecom(all_results):
    """将结果格式化为企微消息格式"""
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")


    markdown_content = f"**APP应用市场线上版本**\n\n> 检查时间: {current_time}\n\n"


    apps = {}
    for key, value in all_results.items():

        if "移动获客" in key:
            app_name = "移动获客"
        elif "巨好播" in key:
            app_name = "巨好播"
        else:
            app_name = "其他"

        if app_name not in apps:
            apps[app_name] = []

        platform = key.replace(f"{app_name}-", "")
        apps[app_name].append(f"- {platform}: {value}")

    for app_name, results in apps.items():
        markdown_content += f"**{app_name}**\n"
        markdown_content += "\n".join(results)
        markdown_content += "\n\n"

    return markdown_content


def main():

    webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=1f9342cb-5f52-4da9-9ad0-93b88f036ee0"


    wecom_robot = WeComRobot(webhook_url)


    apps_info = [
        {
            "name": "移动获客",
            "app_id": "com.mysoft.yunke.llhkb",
            "hw_id": "C111525497",
            "apple_url": "https://apps.apple.com/cn/app/%E7%A7%BB%E5%8A%A8%E8%8E%B7%E5%AE%A2/id6499023668",
            "vivo_url": "https://h5.appstore.vivo.com.cn/#/details?search_word=%E7%A7%BB%E5%8A%A8%E8%8E%B7%E5%AE%A2&search_action=4&app_id=3746005&app_pos=1&source=5&appId=3746005&frompage=searchResultApp&listpos=1"
        },
        {
            "name": "巨好播",
            "app_id": "com.chengguo.jhb",
            "hw_id": "C115385033",
            "apple_url": "https://apps.apple.com/cn/app/%E5%B7%A8%E5%A5%BD%E6%92%AD/id6752237562",
            "vivo_url": "https://h5.appstore.vivo.com.cn/#/details?search_word=%E5%B7%A8%E5%A5%BD%E6%92%AD&search_action=4&app_id=4333508&app_pos=1&source=5&appId=4333508&frompage=searchResultApp&listpos=1"
        }
    ]

    print("开始获取各应用市场版本信息...")
    print("=" * 50)


    crawler = AppVersionCrawler()

    all_results = {}

    try:

        for app_info in apps_info:
            print(f"\n正在获取 {app_info['name']} 的版本信息...")
            app_results = crawler.get_app_versions(app_info)
            all_results.update(app_results)


            print("-" * 40)


        print("\n获取结果:")
        print("=" * 50)
        for platform, version in all_results.items():
            print(f"{platform}: {version}")


        print("\n正在发送企微通知...")
        markdown_content = format_results_for_wecom(all_results)
        success = wecom_robot.send_markdown_message("应用版本检查报告", markdown_content)

        if success:
            print("企微通知发送成功!")
        else:
            print("企微通知发送失败!")

    except Exception as e:
        print(f"发生错误: {str(e)}")

        error_msg = f"应用版本检查失败: {str(e)}"
        wecom_robot.send_text_message(error_msg)
        import traceback
        traceback.print_exc()
    finally:

        crawler.close()


if __name__ == "__main__":
    main()